package org.jiang.springbootdemo.demos.web.test.sort;

/**
 * 归并排序
 */
public class MergeSort {
    public void sort(int[] arr, int left, int right) {
        int mid;
        if (left >= right) {
            return;
        }
        // left 0, mid 1, right 3
        // left 0, mid 0, right 1
        mid = left + (right - left) / 2;
        sort(arr, left, mid);
        sort(arr, mid + 1, right);
        merge(arr, left, mid, right);
    }

    private void merge(int[] arr, int left, int mid, int right) {
        int[] temp = new int[right - left + 1];
        int i = left, j = mid + 1, k = 0;

        while (i <= mid && j <= right) {
            temp[k++] = arr[i] <= arr[j] ? arr[i++] : arr[j++];
        }

        while (i <= mid) {
            temp[k++] = arr[i++];
        }

        while (j <= right) {
            temp[k++] = arr[j++];
        }

        for (i = 0; i < k; i++) {
            arr[left + i] = temp[i];
        }
    }

    public static void main(String[] args) {
        MergeSort m = new MergeSort();
        int[] arr = {2, 4, 7, 5, 8, 1, 3, 6};
        m.sort(arr, 0, 7);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
